var consts = require('../../../util/consts');
var Time = require('../../../util/time');
const {
    checkUserSign,
    getUserSignData,
    saveUserSign,
    getTodayOilLimit,
    getUserPrePorduct,
} = require('../lib/signCache');
const {
    getUserInfo
} = require('../../mission/lib/api');
const {
    formatCoins,
} = require('../../upgrade/lib/action');
const {
    default: BigNumber
} = require('bignumber.js');

var AsyncLock = require('async-lock');
var lock = new AsyncLock({
    timeout: 1000
});


module.exports = function (app) {
    return new Handler(app);
}
const Handler = function (app) {
    this.app = app;
}
const handler = Handler.prototype;


/**
 * 签到列表
 */

handler.signdate = async function (msg, session, next) {
    var uid = session.uid,
        self = this,
        todayDate = Time.getTodayDate();
    //获取本周日期
    if (!uid) {
        next(null, {
            code: consts.Code.ERR,
            msg: consts.Msg.MISSING_PARAMETER
        });
    }
    //用户签到信息
    let userInfo = await getUserInfo.call(this, session, uid);
    if (!userInfo) {
        if (err) {
            next(null, {
                code: consts.Code.ERR,
                msg: err
            })
            return;
        }
    }

    let oilLimit = await getTodayOilLimit.call(this, session, uid);
    let inComeRate = await getUserPrePorduct.call(this,session);
    let getTodayPrice = (key) => {
        key = Number(key);
        if (key < 6) {
            let multi = (key + 2) * 3600; //2-7
            let per_sec_coins = BigNumber(inComeRate).times(multi).times(25);   //更改为原先基础的25倍
            return per_sec_coins
        } else {
            let oil = Math.floor(oilLimit / 2);
            if(oil<= 0) oil = 1;
            return oil; //await getTodayOilLimit.call(this,session,uid);
        }
    }

    //获取缓存
    let hasCache = await checkUserSign.call(this, uid)
    if (hasCache) { //有缓存
        let signData = await getUserSignData.call(this, uid);
        // console.warn(userInfo);
        
        //更新签到数据
        for (let key in signData) {
            let data = signData[key];
            //比较当前日期和今天日期
            let diff = new Date(todayDate).getTime() - new Date(data.date).getTime() >= 0 ? 1 : 0;
            signData[key].can_signle = diff;
            signData[key].realPrice = getTodayPrice(key);
            signData[key].price = key == 6 ? signData[key].realPrice : formatCoins(signData[key].realPrice);
            if (signData[key].is_single) { //已经签到 不能签到
                signData[key].can_signle = 0
            }
            signData[key].is_today = todayDate === data.date ? 1 : 0; //是不是今天
        }
        await saveUserSign.call(this, {
            uid: uid,
            data: signData
        })
        next(null, {
            code: consts.Code.SUC,
            msg: consts.Msg.RESULT_SUCCESS,
            data: signData
        });
        return;
    } else { //没有缓存
        //用户签到信息
        let userInfo = await getUserInfo.call(this, session, uid);
        if (!userInfo) {
            if (err) {
                next(null, {
                    code: consts.Code.ERR,
                    msg: err
                })
                return;
            }
        } else {
            //本周每天日期
            let weekDate = Time.getWeekDay();
            //初始化签到列表
            let signData = [];
            weekDate.forEach((element, key) => {
                let type = key == 6 ? consts.MoneyType.OIL : consts.MoneyType.GOLD;
                //奖品数量
                let price = getTodayPrice(key);
                //比较当前日期和今天日期
                let diff = new Date(todayDate).getTime() - new Date(element).getTime() >= 0 ? 1 : 0;
                signData.push({
                    is_single: 0, //没有签到
                    realPrice: price,
                    price: key == 6 ? Number(price).toFixed(2) : formatCoins(price), //奖品
                    type: type, //类型
                    is_today: todayDate === element ? 1 : 0, //是不是今天
                    date: element,
                    can_signle: diff,
                })
            });

            await saveUserSign.call(this, {
                uid: uid,
                data: signData
            })
            next(null, {
                code: consts.Code.SUC,
                msg: consts.Msg.RESULT_SUCCESS,
                data: signData
            });
        }
    }
}
/**
 * 处理用户签到功能
 */
handler.signin = async function (msg, session, next) {
    let uid = session.uid,
        self = this,
        date = msg.date,
        weekDate = Time.getWeekDay();

    //验证用户登陆
    if (!uid) {
        next(null, {
            code: consts.Code.ERR,
            msg: consts.Msg.MISSING_PARAMETER
        })
    }
    //检查签到日期是否合法
    let t = new Date(date);
    if (t.getTime() > Date.now()) {
        next(null, {
            code: consts.Code.ERR,
            msg: consts.Msg.SIGN_CANT
        })
    }


    let userInfo = await getUserInfo.call(this, session, uid);
    if (userInfo) {
        lock.acquire(consts.LockKey.SIGN_GET + uid, async function () {
            let signData = await getUserSignData.call(self, uid);
            if (signData) {
                //检测是否已经签到过
                for (let key in signData) {
                    let data = signData[key];
                    if (data.date == date) {
                        if (data.is_single == 1) { //已经签到
                            next(null, {
                                code: consts.Code.ERR,
                                msg: consts.Msg.SIGN_DONE
                            })
                            return;
                        } else { //进行签到
                            data.is_single = 1;
                            data.can_signle = 0;

                            //发放奖励
                            if (data.type === consts.MoneyType.OIL) {
                                //操作石油
                                self.app.rpc.login.loginRemote.addOil(session, uid, session.frontendId, data.realPrice, consts.OIL_ADD_TYPE.SIGN,'', function (err, errMsg) {
                                    if (err) {
                                        next(null, {
                                            code: consts.Code.ERR,
                                            msg: consts.Msg.DATA_ERR
                                        })
                                        return;
                                    } else {
                                        next(null, {
                                            code: consts.Code.SUC,
                                            msg: consts.Msg.RESULT_SUCCESS
                                        })
                                    }
                                });
                            } else {
                                //操作金币
                                self.app.rpc.login.loginRemote.addCoins(session, uid, session.frontendId, data.realPrice, true, function (err, msg) {
                                    next(null, {
                                        code: consts.Code.SUC,
                                        msg: consts.Msg.RESULT_SUCCESS
                                    })
                                })

                            }

                        }
                        
                    }
                }
                //保存数据
                await saveUserSign.call(self, {
                    uid: uid,
                    data: signData
                })
            } else {
                next(null, {
                    code: consts.Code.ERR,
                    msg: consts.Msg.DATA_ERR
                })
            }
        })
    }



}
